package com.milkshopbackend.milkshop.Service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.milkshopbackend.milkshop.Service.ProductService;
import com.milkshopbackend.milkshop.entity.Product;
import com.milkshopbackend.milkshop.entity.ProductDTO;
import com.milkshopbackend.milkshop.mapper.ProductMapper;
import com.milkshopbackend.milkshop.util.CacheClient;
import com.milkshopbackend.milkshop.common.RedisConstants;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.springframework.scheduling.annotation.Scheduled;

import javax.annotation.Resource;
import java.time.LocalDateTime;

@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements ProductService {

    @Resource
    private ProductMapper productMapper;

    @Resource
    private CacheClient cacheClient;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    @Transactional
    public Product createProduct(ProductDTO productDTO) {
        Product product = new Product();
        BeanUtils.copyProperties(productDTO, product);
        product.setCreateTime(LocalDateTime.now());
        product.setUpdateTime(LocalDateTime.now());
        productMapper.insert(product);
        // 清理相关缓存
        redisTemplate.delete(RedisConstants.HOT_PRODUCT_LIST_KEY);
        return product;
    }

    @Override
    @Transactional
    public Product updateProduct(Long id, ProductDTO productDTO) {
        Product  product = productMapper.selectById(id);
        if (product==null) {
            throw new RuntimeException("商品不存在");
        }
        BeanUtils.copyProperties(productDTO, product);
        product.setUpdateTime(LocalDateTime.now());
        productMapper.updateById(product);
        // 清理相关缓存
        redisTemplate.delete(RedisConstants.PRODUCT_KEY_PREFIX + id);
        redisTemplate.delete(RedisConstants.HOT_PRODUCT_LIST_KEY);
        return product;
    }

    @Override
    @Transactional
    public void deleteProduct(Long id) {
        productMapper.deleteById(id);
        // 清理相关缓存
        redisTemplate.delete(RedisConstants.PRODUCT_KEY_PREFIX + id);
        redisTemplate.delete(RedisConstants.HOT_PRODUCT_LIST_KEY);
    }

    @Override
    public Product getProduct(Long id) {
        return cacheClient.getWithPassThrough(
            RedisConstants.PRODUCT_KEY_PREFIX,
            String.valueOf(id),
            Product.class,
            k -> productMapper.selectById(Long.valueOf(k)),
            RedisConstants.PRODUCT_TTL,
            java.util.concurrent.TimeUnit.SECONDS
        );
    }

    @Override
    public Page<Product> listProducts(Integer page, Integer size, String keyword) {
        Page<Product> pageParam = new Page<>(page, size);
        LambdaQueryWrapper<Product> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.hasText(keyword)) {
            wrapper.like(Product::getName, keyword)
                    .or()
                    .like(Product::getDescription, keyword);
        }
        wrapper.orderByDesc(Product::getCreateTime);
        return productMapper.selectPage(pageParam, wrapper);
    }

    @Override
    public void updateStatus(Long id, boolean status) {
       Product product = productMapper.selectById(id);
        if (product==null) {
            throw new RuntimeException("商品不存在");
        }
        product.setStatus(status);
        product.setUpdateTime(LocalDateTime.now());
        productMapper.updateById(product);
    }

    /**
     * 查询销量最高的热门商品列表（首页用）
     */
    public List<Product> listHotProducts(int topN) {
        // 1. 先查缓存
        String key = RedisConstants.HOT_PRODUCT_LIST_KEY;
        Object cache = redisTemplate.opsForValue().get(key);
        if (cache != null && cache instanceof List) {
            return (List<Product>) cache;
        }
        // 2. 查数据库
        LambdaQueryWrapper<Product> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(Product::getSales);
        wrapper.last("limit " + topN);
        List<Product> hotList = productMapper.selectList(wrapper);
        // 3. 写入缓存
        redisTemplate.opsForValue().set(key, hotList, RedisConstants.HOT_PRODUCT_LIST_TTL, TimeUnit.SECONDS);
        return hotList;
    }

    /**
     * 定时刷新热门商品缓存（每5分钟）
     */
    @Scheduled(cron = "0 */5 * * * ?")
    public void refreshHotProductCache() {
        LambdaQueryWrapper<Product> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(Product::getSales);
        wrapper.last("limit 10");
        List<Product> hotList = productMapper.selectList(wrapper);
        redisTemplate.opsForValue().set(RedisConstants.HOT_PRODUCT_LIST_KEY, hotList, RedisConstants.HOT_PRODUCT_LIST_TTL, TimeUnit.SECONDS);
    }
}
